package com.app.studyroom.model;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.view.View;

import androidx.annotation.Nullable;


import java.util.ArrayList;
import java.util.List;

public class OverlayFrameView extends View {

    private final List<Classroom.FrameOverlay> frameList = new ArrayList<>();
    private final Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);

    public OverlayFrameView(Context context) {
        super(context);
        init();
    }

    public OverlayFrameView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public OverlayFrameView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        paint.setStyle(Paint.Style.STROKE);
    }

    public void setFrameList(List<Classroom.FrameOverlay> list) {
        frameList.clear();
        if (list != null) {
            frameList.addAll(list);
        }
        invalidate(); // 触发重绘
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        float density = getResources().getDisplayMetrics().density;

        for (Classroom.FrameOverlay frame : frameList) {
            paint.setColor(parseColorSafe(frame.borderColor));
            paint.setStrokeWidth(frame.borderWidth * density);
            float left = frame.x * density;
            float top = frame.y * density;
            float right = (frame.x + frame.width) * density;
            float bottom = (frame.y + frame.height) * density;
            canvas.drawRect(new RectF(left, top, right, bottom), paint);
        }
    }

    private int parseColorSafe(String colorStr) {
        try {
            return android.graphics.Color.parseColor(colorStr);
        } catch (Exception e) {
            return android.graphics.Color.RED;
        }
    }
}
